package com.atguigu4.exer;

import com.atguigu3.util.JDBCUtils;
import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.util.Scanner;

public class Exer1Test {
    @Test
    public void testInsert() {
        Scanner scan = new Scanner(System.in);
        System.out.println("请输入用户名：");
        String name = scan.next();
        System.out.println("请输入用户邮箱：");
        String email = scan.next();
        System.out.println("请输入用户生日：");
        String birthday = scan.next();

        String sql = "insert into customers(name,email,birth) values (?,?,?)";
        int insertCount = update(sql, name, email, birthday);
        if (insertCount > 0) {
            System.out.println("添加成功");
        } else {
            System.out.println("添加失败");
        }
    }


    //课后练习一：
    public int update(String sql, Object... args) {
        Connection conn = null;
        PreparedStatement ps = null;
        try {
            conn = JDBCUtils.getConnection();
            ps = conn.prepareStatement(sql);
            for (int i = 0; i < args.length; i++) {
                ps.setObject(i + 1, args[i]);
            }
            /**
             *
             * ps.execute();
             * 如果执行的是查询操作，有返回结果，则返回true
             *如果执行的是增、删、改操作，没有返回结果，则返回false
             */
            //方式一：
            // ps.execute();

            //方式二：
            return ps.executeUpdate();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            JDBCUtils.closeResource(conn, ps);
        }
        return 0;
    }
}
